const router = require('koa-router')()
const lists = require('../model/lists')
const koaBody = require('koa-bodyparser');
const send = require('send');
const fs = require('fs');
const path = require('path');

// 获取文件列表
router.get('/files', async (ctx) => {
    const uploadsPath = path.join(__dirname, '..', 'uploads');
    const files = fs.readdirSync(uploadsPath).filter(file => file.endsWith('.pdf'));
    ctx.body = files.map(filename => ({ name: filename }));
});

// 删除文件
router.delete('/files/:name', async (ctx) => {
    const filename = ctx.params.name;
    const uploadsPath = path.join(__dirname, '..', 'uploads');
    const filepath = path.join(uploadsPath, filename);
    if (fs.existsSync(filepath)) {
        fs.unlinkSync(filepath);
        ctx.status = 200;
    } else {
        ctx.status = 404;
    }
});

router.post('/upload',koaBody(), async (ctx) => {
    const file = ctx.request.files.file;
    const uploadsPath = path.join(__dirname, '..', 'uploads');
    const filePath = path.join(uploadsPath, file.name);
    try {
        // 将文件保存到服务器
        const reader = fs.createReadStream(file.path);
        const writer = fs.createWriteStream(filePath);
        reader.pipe(writer);
        console.log('文件保存成功:', filePath);
    
        ctx.body = { message: '文件上传成功', filePath: filePath }; // 返回上传成功的消息及文件路径
      } catch (error) {
        console.error('文件保存失败:', error);
        ctx.status = 500;
        ctx.body = { message: '文件上传失败' };
      }
});

module.exports = router;